package zl.osimall.front.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import zl.osimall.common.bean.Addr;
import zl.osimall.common.bean.User;
import zl.osimall.common.exception.SteduException;
import zl.osimall.common.service.AddrService;
import zl.osimall.common.service.CartService;
import zl.osimall.common.service.OrderService;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user/addr")
public class AddrController {
    @Autowired
    private AddrService addrService;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;

    @RequestMapping("/toAddr")
    public String toAddr(HttpSession session, Model m){
        User user =(User) session.getAttribute("user");
        List<Addr> addrList = addrService.selectByUserId(user.getId());
        m.addAttribute("addrList", addrList);
        return "user/addr";
    }


    @RequestMapping("/addr")
    public String addr(String orderId, String paypwd, HttpSession session, Model m){
        try {
            User user = (User) session.getAttribute("user");
            Integer userId = user.getId();
            orderService.pay(orderId, userId, paypwd);
            return "redirect:/user/order/list";
        }  catch (SteduException e){
            e.printStackTrace();
            m.addAttribute("errMsg", e.getMessage());
            return "user/error";
        }
    }

    @GetMapping("/addAddr")
    public String addAddr(HttpSession session, Model m){
        return "user/addAddr";
    }


    @PostMapping ("/addAddr")
    public String addAddr(Addr addr , HttpSession session){
            User user = (User) session.getAttribute("user");
            addr.setUserId(user.getId());
            if (addr.getStatus()==null){
                addr.setStatus(0);
            }
            addrService.insert(addr);
            return "redirect:/user/addr/toAddr";

    }

    @GetMapping("/updateAddr")
    public String updateAddr(Integer id, Model m){
        Addr addr = addrService.selectById(id);
        m.addAttribute("addr", addr);
        return "user/updateAddr";
    }


    @PostMapping("/updateAddr")
    public String updateAddr(Addr addr , HttpSession session){
        User user = (User) session.getAttribute("user");
        addr.setUserId(user.getId());
        addrService.update(addr);
        return "redirect:/user/addr/toAddr";

    }

    @GetMapping("/deleteAddr")
    public String deleteAddr(Integer id ){
        addrService.delete(id);
        return "redirect:/user/addr/toAddr";
    }
}
